angular.module('UCX.Cmis')
.controller 'CreateFolderCtrl', ($scope, $uibModalInstance,Utils,$translate)->
  $scope.folderName = ''
  $scope.handleEnterKey=(e)->
    if e.which==13
      $scope.ok()
  $scope.ok = ()->
    if Utils.isForbiddenFolderName($scope.folderName)
      $translate('folder_name_forbidden',).then (text)->
        Utils.warning(text)
      return
    if Utils.containIllegalChar($scope.folderName)
      $translate('641').then(
        (result)->
          result = result.replace('&lt;','<').replace('&gt;','>')
          Utils.warning(result)
      ,
        ()->)
      return
    if $scope.folderName.length==0
      $translate('folder_name_null').then (text)->
        Utils.warning(text)
      return
    $uibModalInstance.close($scope.folderName)
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')

.controller "UploadDrnCtrl", ($scope, $uibModalInstance, dropFile, Loading, CmisService, folder, Utils, $translate, parentScope, $timeout,UploadQueue)->
  $scope.tempFolder = $scope.currentFolder
  $scope.dropFile = dropFile
  $scope.file = dropFile
  $scope.freePreviewPages = 3
  $scope.ok = ()->
    file = if dropFile then dropFile else $scope.file
    ext = Utils.getFileExt(file.name)
    if !Utils.isAllowExtension(file)
      $translate('file_type_error').then (text)->
        Utils.warning(text)
      return false
    freePreviewPages = $scope.freePreviewPages
    UploadQueue.add(
      file,
      $scope.tempFolder.id,
      {
      'cmis:name': file.name,
      'cmis:objectTypeId': 'smx:drmdoc'
      'smxj:freePreviewPages': parseInt(freePreviewPages)
      },
      "none"
    )
    $uibModalInstance.close({file:$scope.file, freePreviewPages:$scope.freePreviewPages})
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')

  $scope.isDisabled = ()->
    !$scope.file || $scope.freePreviewPages < 0

.controller "createInviteModal", ($scope, $uibModalInstance, isOwner, document, sendToOwner, sending, Utils, CmisService, ModelService)->
  $scope.isOwner=isOwner
  $scope.document=document
  $scope.sending=sending
  $scope.sendToOwner=sendToOwner
  $scope.newEmail=''
  $scope.emails=[]
  $scope.emailPattern=/^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/
#  $scope.deleteArrayItem=(arr,index)->
#    rest=arr.arr.slice(index + 1 || arr.length)
#    arr.length = index < 0 ? arr.length + index : index
#    arr.push.apply(arr, rest)
  $scope.delete=(index)->
    $scope.emails.splice(index,1)
  $scope.addNewEmail=()->
    isValidEmail=$scope.emailPattern.test($scope.newEmail)
    isEmailEmpty=$scope.newEmail==''
    if(isValidEmail)
      $scope.emails.push({id:$scope.id,emailAddress:$scope.newEmail})
      $scope.newEmail=''
    else if !isValidEmail&&!isEmailEmpty
      Utils.warning "Invalid Email"
    else if isEmailEmpty
      Utils.warning "Email Not Null"
  $scope.getEmailList = ()->
    emailList = []
    for email in $scope.emails
      if email.emailAddress != ''
        emailList.push email.emailAddress
    if $scope.newEmail != ''
      emailList.push $scope.newEmail
    emailList
  $scope.isValid = ()->
    emailList = $scope.getEmailList()
    isValid = if emailList.length then true else false
    for email in emailList
      if !$scope.emailPattern.test(email)
        isValid = false
    isValid
  $scope.ok=()->
    token=CmisService.token
    postUrl=CmisService.baseUrl+'api/v3/room/request-access?access-token='+token
    #emailList 是推入下方的 那个 email的表
    documentId = if document then document.id else ''
    roomId=ModelService.getRoomId()
    isValid = $scope.isValid()
    if isValid
      emailList = $scope.getEmailList()
      postData={
        rid:roomId
        did:documentId
        invitee_list:emailList
        message_to_owner:$scope.message
      }
      $.ajax(
        {
          type:'POST'
          url:postUrl,
          data:postData,
          dataType:'json',
          success:()->
            Utils.success "Success!"
            $uibModalInstance.close()
          error:(data)->
            jsonData = JSON.parse(data.responseText)
            Utils.warning jsonData.message
            $scope.sending=false
            $scope.sendToOwner=sendToOwner
        }
      )
      $scope.sending=true
      $scope.sendToOwner='Sending'
    else
      Utils.warning "Invalid Email"
  $scope.cancel=()->
    $uibModalInstance.dismiss('cancel')
.controller "RenameCtrl", ($scope, $uibModalInstance,CmisService,file,$timeout,Utils,$rootScope,$translate,scope,ApiService)->
  $scope.repository = CmisService.repository=='fxcld'
#  $uibModalInstance.opened 是一个promise类 那么就有promise类的属性
  $scope.file = file
  #  $scope.oldName 存储原来的名字
  $scope.oldName = file.name
  #  $scope.newName 作为双向绑定变量
  $scope.newName = file.name
  CmisServiceSession = CmisService.session
  # 打开会直接focus
  $scope.ok = ()->
    if $scope.newName.length==0
      $translate('folder_name_null',).then (text)->
        Utils.warning(text)
      return
    if Utils.containIllegalChar($scope.newName)
      $translate('641').then(
        (result)->
          result = result.replace('&lt;','<').replace('&gt;','>')
          console.log(result)
          Utils.warning(result)
      ,
        ()->)
      return
    if $scope.newName != $scope.oldName
#      立刻马上显示结果不等待结果
      file.name = $scope.newName
      url = CmisServiceSession.defaultRepository.rootFolderUrl+'?objectId='+file.id
      postData = {
        'propertyId[0]':'cmis:name'
        'propertyValue[0]':$scope.newName
        'cmisaction':'update'
        'succinct':'true'
      }
      $.ajax(
        {
          type: 'POST'
          url:url,
          beforeSend: (request)->
            request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
          data: postData
          success: (data)->
            $translate('rename_succ').then (text)->
              Utils.success(text)
            Utils.showFilenameTooltip(file)
            Utils.parentHasRenamed=true
            if file.isDocument()
#         更新版本 以及自己的id
#          file.getVersions(null,null,true)
              parent = file.getParent()
              Utils.sendGaEvent("File", "Rename", file.id)
              file.createActivity "update-document", {name: $scope.newName}
            else
              scope.updateLeftAsideFolderTree()
              file.path = data.succinctProperties['cmis:path']
              Utils.sendGaEvent("Folder", "Rename", file.id)
              file.createActivity "modify-folder", {name: $scope.newName}
          error: (r)->
            file.name = $scope.oldName
            newPath = $scope.file.getParent().path+'/'+$scope.newName
            #            console.log(r.responseJSON)
            console.log(r.responseJSON)
            $scope.file.path.lastIndexOf('')
            Utils.translateErrorMsg(r.responseJSON,{path:newPath})
        }
      )

    #      CmisServiceSession.updateProperties(
    #        file.id,
    #        {'cmis:name':$scope.newName}
    #      ).notOk (r)->
    #        file.name = $scope.oldName
    #        jsonData = JSON.parse(r.text)
    #        Utils.warning(jsonData.message)
    #      .ok (data)->
    #        Utils.showFilenameTooltip(file)
    #        if file.isDocument()
    ##         更新版本 以及自己的id
    ##          file.getVersions(null,null,true)
    #          parent = file.getParent()
    #          file.createActivity "update-document", {name: $scope.newName}
    #        else
    #          file.path = data.succinctProperties['cmis:path']
    #          file.createActivity "modify-folder", {name: $scope.newName}
    $uibModalInstance.close(file)
  #  enter button 相当于执行了 ok
  $scope.handleEnterKey=(e)->
    if e.which==13 && $scope.newName.length>0
      $scope.ok()
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
  #  部分选择 文件名
  $scope.rangeSelect=(textField,start,end)->
#    textField 可以是 document.getElementById('text') 也可以是 $('#text') 是一个对象
#    start 表示的是 文字高亮的起始点 但是不包含该点
#    end   表示  文字高亮区的结束点  包含
    if textField.createTextRange
#   ie and opera
      selRange = field.createTextRange()
      selRange.collapse(true)
      selRange.moveStart('character', start)
      selRange.moveEnd('character', end)
      selRange.select()
      textField.focus()
    else if textField.setSelectionRange
#      chrome firefox safari
      textField.focus()
      textField.setSelectionRange(start, end)
    else if typeof textField.selectionStart != 'undefined'
#      if not support
      textField.selectionStart = start
      textField.selectionEnd = end
      textField.focus()
  #      只有当 input框的内容出现时候 才去执行 操作
  $scope.domReady=()->
    if !($('#file-name')[0] && $('#file-name')[0].value)
      $timeout(()->
        $scope.domReady()
      ,300)
    else
      startIndex=0
      endIndex=$scope.oldName.lastIndexOf('.')
      if endIndex==-1
        endIndex=$scope.oldName.length
      $scope.rangeSelect($('#file-name')[0],startIndex,endIndex)
  $uibModalInstance.opened.then(()->
#    这个地方配合 html5 的autofocus 使用 因为 源码modal.js 有 autofocus的操作有时候会导致 选中出问题
    if CmisService.repository == 'fxcld'
      return
    $scope.domReady()
  )
.controller "LoadingController", ($scope, content)->
  $scope.content = content
.controller 'ConfirmController', ($scope, $uibModalInstance, content, title, confirmBtnText, cancelBtnText, $translate) ->
  $scope.content = content
  $scope.confirmTitle = title || $translate.instant('confirm')
  $scope.confirmBtnText = confirmBtnText || $translate.instant('ok')
  if cancelBtnText!=null
    $scope.cancelBtnText = cancelBtnText || $translate.instant('cancel')
  $scope.ok = ()->
    $uibModalInstance.close()
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
.controller 'uploadNewVersionCtrl',($scope, $uibModalInstance , parentScope ,rootScope,$translate, Utils, CmisService , Loading,UploadQueue, content)->
  $scope.content=content
  $scope.confirmTitle = $translate.instant('confirm')
  $scope.confirmBtnText = $translate.instant('ok')
  $scope.cancelBtnText = $translate.instant('cancel')
  CmisServiceSession=CmisService.session
  $scope.rootScope=parentScope
#  console.log parentScope
  $scope.ok = ()->
    $translate('uploading').then (text)->
      if rootScope.progressHandler
        rootScope.progressHandler.dismiss()
        UploadQueue.modal=false
      Loading.open text

    console.log parentScope.modifyNewFile
    parentScope.setContentStream(parentScope.modifyNewFile)
    $uibModalInstance.close()
    return
#
#    if parentScope.tempFile.isVersionSeriesCheckedOut
#      parentScope.checkIn(parentScope.modifyNewFile)
#    else
#      CmisServiceSession.checkOut(parentScope.tempFile.id).ok (checkOutObj)->
#        parentScope.checkIn(parentScope.modifyNewFile)
#      .notOk (r)->
#        if Utils.handleCmis401Error(r)
#          return
#        Utils.isUploadNewVersioning = false
#        Loading.close()
#        jsonData = JSON.parse(r.text)
#        Utils.warning(jsonData.message)
#    $uibModalInstance.close()
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
#.controller 'userNotAllowedUpload',($scope,toastr,content)->
#  $scope.content = content
#  $scope.ok=()->
#    $uibModalInstance.close()
.controller 'adjustCDRMPermissionCtrl',($scope, $uibModalInstance,$translate, file, data, Utils, CmisService, Loading,UploadQueue, ApiService)->
  #  console.log parentScope
  $scope.ok = ()->
    $scope.$emit('set-file-cDRM-permission',file)
    $uibModalInstance.close()
    return
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
.controller "moveToFolderModal", ($scope, $uibModalInstance, files, currentFolder, CmisService, Utils,ModelService,$rootScope,$translate,scope)->
  CmisServiceSession = CmisService.session
  $scope.selected = null
  $scope.currentFolder = currentFolder
  $scope.destFolder = currentFolder
  $scope.moveTargetId = ''
  objectIds = []
  for file in files
    objectIds.push(file.id)
  if files.length==1 && !files[0].isDocument()
    $scope.moveTargetId = files[0].id
  $scope.totalMovedItemNum = files.length
  $scope.successMoveCount = 0
  $scope.failedMoveCount = 0
  $scope.enterIn = (folder)->
    if !$scope.currentFolder.isCDRMFolder() && folder.isCDRMFolder()
      Utils.warning($translate.instant('mov_non_cDrm_to_cDrm'))
    else
      $scope.destFolder = folder
      $scope.isDisabled()
  $scope.backOf = (folder)->
    parentFolder = folder.getParent()
    if !parentFolder.isCDRMFolder() && folder.isCDRMFolder()
      Utils.warning($translate.instant('mov_cDrm_to_non_cDrm'))
    else
      $scope.destFolder = parentFolder
      $scope.isDisabled()
  successCallback=(objectId, sourceFolder, targetFolder,lastErr)->
    if !lastErr
      $scope.successMoveCount++

    if $scope.successMoveCount + $scope.failedMoveCount == $scope.totalMovedItemNum
      if $scope.successMoveCount == 1
        $translate('one_move_success').then((result)->
          Utils.success(result)
        )
      else
        if $scope.successMoveCount ==0
          return false
        else
          $translate('more_move_success',{
            successNum:$scope.successMoveCount
          }).then((result)->
            Utils.success(result)
          )
    if lastErr
      return false
    else
      file = ModelService.getObjectById(objectId)
      file.refresh()
      if !file.isDocument()
        if currentFolder.id == sourceFolder.id
          sourceFolder=currentFolder
        if sourceFolder.folderList&&sourceFolder.folderList.length
          index = i for folder,i in sourceFolder.folderList when file.id == folder.id
          sourceFolder.folderList.splice(index,1)
        #              和下面同样的问题 空文件夹 移入的时候会报错
        if !targetFolder.folderList
          targetFolder.folderList=[]
        targetFolder.folderList.push file

        file.loadChildren = false
        file.folderList = null
        file.children = []
        Utils.sendGaEvent("Folder", "Move", file.id)
        file.createActivity "move-folder", {name: file.name, from_folder_name: sourceFolder.name, to_folder_name: targetFolder.name}
      else
        Utils.sendGaEvent("File", "Move", file.id)
        file.createActivity "move-document", {name: file.name, from_folder_name: sourceFolder.name, to_folder_name: targetFolder.name}

      index = i for folder,i in sourceFolder.children when file.id == folder.id
      sourceFolder.children.splice(index,1)
      #            新创建的文件夹 移入文件会报错
      if !targetFolder.children
        targetFolder.children=[]
      targetFolder.children.push(file)
      scope.multipleChooseFiles=[]
      scope.choseFile=scope.currentFolder
      scope.cancelSelectMode(true)
      scope.scopeApply(500)
  $scope.isDisabled=()->
    currentFolder.path == $scope.destFolder.path || !$scope.destFolder.allowableActions.canCreateFolder || !$scope.destFolder.allowableActions.canCreateDocument  || objectIds.indexOf($scope.destFolder.id)>-1 || $scope.destFolder.isReadonly()
  $scope.ok=()->
#    处理 移动事件
    delay=0
    sourceFolder=currentFolder
    targetFolder=$scope.destFolder
    targetId = $scope.destFolder.id
    sourceId = currentFolder.id
    ajaxcall = (objectId)->
      sourceId = ModelService.getObjectById(objectId).getParent().id
      options = {}
      options.objectId = objectId
      options.cmisaction = 'move'
      options.targetFolderId = targetId
      options.sourceFolderId = sourceId
      $.ajax(
        {
          type: 'POST'
          url:CmisService.session.defaultRepository.rootFolderUrl,
          beforeSend: (request)->
            request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
          data: options
          success: ()->
            movedObj=ModelService.getObjectById(objectId)
            sourceFolder=movedObj.getParent()
            successCallback(objectId, sourceFolder, targetFolder)
          error: (r)->
            $scope.failedMoveCount++
            if $scope.failedMoveCount+$scope.successMoveCount==$scope.totalMovedItemNum
              successCallback(objectId, sourceFolder, targetFolder,true)
            path = ModelService.allFiles[targetId].path + '/' + ModelService.allFiles[objectId].name
            console.log(r.responseJSON)
            return scope.translateErrorMsg(r.responseJSON, {
              path: path
            })
        }
      )
    for objectId in objectIds
      setTimeout((objectId)->
        ajaxcall(objectId)
      ,delay*2000,objectId)
      delay++
    $uibModalInstance.close()

  $scope.cancel=()->
    $uibModalInstance.dismiss()

.controller 'deleteModal', ($scope,$uibModalInstance,files,CmisService,currentFolder,ModelService,Utils,$rootScope,$q,$translate, $timeout, scope, searchModeIsOn)->
  CmisServiceSession = CmisService.session
  $scope.pathIsLoading = if files.length == 1 then true else false
  $scope.files=files
  $scope.hasFolders= true for file in files when !file.isDocument()
  $scope.hasDocs= true for file in files when file.isDocument()

  if $scope.pathIsLoading
    $scope.pathIsLoading = false
#    if !files[0].isDocument()
#      $scope.pathIsLoading = false
#    else
#      if files[0].getPaths
#        files[0].getPaths((success)->
#          console.log success
#          $scope.pathIsLoading = false
#        ,
#          (error)->
#            console.log(error)
#            $rootScope.translateErrorMsg(error)
#        )
#      else
#        $scope.pathIsLoading = false


  $scope.currentFolder=currentFolder
  $scope.allFiles=ModelService.allFiles

  $scope.successDeleteFileNumber=0
  $scope.unDeleteFileNumber=0
  $scope.isNeedDeleteSuccessCallback=()->
    if $scope.successDeleteFileNumber+$scope.unDeleteFileNumber==$scope.totalDeleteNum && $scope.successDeleteFileNumber!=0
      if $scope.successDeleteFileNumber==1
        num=$scope.successDeleteFileNumber
        #        successCallbackMSG=$scope.successDeleteFileNumber+' file removed'
        $translate('one_file_remove',{num:num}).then (text)->
          Utils.success(text)
      else
        num=$scope.successDeleteFileNumber
        #        successCallbackMSG=$scope.successDeleteFileNumber+' files removed'
        $translate('multi_files_remove',{num:num}).then (text)->
          Utils.success(text)
      scope.multipleChooseFiles = []
      #      $scope.getChildren($scope.currentFolder)
      scope.choseFile = $scope.currentFolder
      $scope.successDeleteFileNumber=0
      $scope.unDeleteFileNumber=0
      scope.cancelSelectMode()
#      scope.updateLeftAsideFolderTree()
#      $timeout(()->
#        $rootScope.$apply()
#      ,0)
  deleteFolder=(folderForDel)->
    if !folderForDel.allowableActions.canDeleteObject
      warningMsg='You do not have permission to delete this Folder '+folderForDel.name
      $scope.unDeleteFileNumber++
      $scope.isNeedDeleteSuccessCallback()
      Utils.warning(warningMsg)
    else
      parent = folderForDel.getParent()
      CmisServiceSession.deleteTree(folderForDel.id, true)
      .ok ()->
      # absolute parent
        # folder tree
        index = i for folder,i in parent.folderList when folderForDel.id == folder.id
        parent.folderList.splice(index,1)
        # children
        index = i for folder,i in parent.children when folderForDel.id == folder.id
        if index!=-1
          parent.children.splice(index,1)
      # relative parent
        if searchModeIsOn
          relaPare = $scope.currentFolder
          index = i for folder,i in relaPare.children when folderForDel.id == folder.id
          relaPare.children.splice(index,1)
        scope.choseFile = $scope.currentFolder
        parent.createActivity "delete-folder", {name: folderForDel.name,from_folder_name:parent.name, del_id:folderForDel.id}
        $scope.successDeleteFileNumber++
        $scope.isNeedDeleteSuccessCallback()
      .notOk (r)->
        if Utils.handleCmis401Error(r)
          return
        jsonData = JSON.parse(r.text)
        $scope.unDeleteFileNumber++
        $scope.isNeedDeleteSuccessCallback()
        scope.translateErrorMsg(jsonData)
  #        Utils.warning(jsonData.message)
  deleteFile=(document,allVersionCount)->
    if !document.allowableActions.canDeleteObject
      warningMsg='You do not have permission to delete this Folder '+document.name
      $scope.unDeleteFileNumber++
      $scope.isNeedDeleteSuccessCallback()
      Utils.warning(warningMsg)
    else
      CmisServiceSession.deleteObject(document.id, true)
      .ok ()->
      # absolute parent
        absoluteParent = document.getParent()
        index = i for tempFile,i in absoluteParent.children when document.id == tempFile.id
        absoluteParent.children.splice(index,1)
      # relative parent
        if searchModeIsOn
          parent = $scope.currentFolder
          index = i for tmp,i in parent.children when tmp.id == document.id
          #        console.log('deleteFile',index)
          if index!=-1
            parent.children.splice(index,1)
        if allVersionCount
#          删单个多重归档，全选的时候
          $scope.successDeleteFileNumber+=allVersionCount
        else
          $scope.successDeleteFileNumber++
        #        console.log('delete方法',$scope.successDeleteFileNumber)
        $scope.choseFile = $scope.currentFolder
        $scope.isNeedDeleteSuccessCallback()
        absoluteParent.createActivity "delete-document", {name: document.name,from_folder_name:absoluteParent.name, del_id:document.id}
#        $scope.currentFolder.getChildren $scope, ()->
#          $scope.children = $scope.currentFolder.children
#          $scope.multipleChooseFiles = []
#          $scope.choseFile = $scope.currentFolder
#          document.createActivity "delete-document", {name: document.name,from_folder_name:parent.name}
#        ,
#          null
#        ,
#          true
      .notOk (r)->
        if Utils.handleCmis401Error(r)
          return
        jsonData = JSON.parse(r.text)
        $scope.unDeleteFileNumber++
        $scope.isNeedDeleteSuccessCallback()
        scope.translateErrorMsg(jsonData)
  #        Utils.warning(jsonData.message)
  removeFromFolder=(file,folderId)->
    options = {}
    options.succinct=true
    options.objectId = file.id
    options.cmisaction = 'removeObjectFromFolder'
    options.folderId = folderId
    $.ajax(
      {
        type: 'POST'
        url:CmisService.session.defaultRepository.rootFolderUrl,
        beforeSend: (request)->
          request.setRequestHeader("Authorization", 'Bearer ' + CmisService.token)
        async: false
        data: options
        success: ()->
#          $scope.currentFolder.id 全局变量
          if folderId == $scope.currentFolder.id
            parent=$scope.currentFolder
            index = q for tmp,q in parent.children when tmp.id == file.id
            if index!=-1
              parent.children.splice(index,1)
          if parent
            $scope.choseFile = $scope.currentFolder
          folder=ModelService.allFiles[folderId]
          file.createActivity "remove-document", {name: file.name,from_folder_name:folder.name}
          $scope.successDeleteFileNumber++
          $scope.isNeedDeleteSuccessCallback()
        error: (r)->
          scope.translateErrorMsg(r.responseJSON)
          $scope.unDeleteFileNumber++
          $scope.isNeedDeleteSuccessCallback()
      }
    )
  totalDeleteCount=(files)->
    $scope.totalDeleteNum=0
#    if files.length>1
    $scope.totalDeleteNum=files.length
#    else
##      多重归档file 和 非多重file 处理
#      if files[0].isDocument()
#        if files[0].paths && files[0].paths.length>1
#          if i.paths.length == $('ul[data-id="'+i.id+'"] :checked').length
#            $scope.totalDeleteNum+=1
#          else
#          $scope.totalDeleteNum += $('ul[data-id="'+files[0].id+'"] :checked').length
#        else
#        $scope.totalDeleteNum=1
#      else
#        $scope.totalDeleteNum=1
    $scope.totalDeleteNum
  deleteController=(files)->
    if files.length>1
      for i in files
        if i.isDocument()
#          if i.paths.length>1
#            removeFromFolder(i,currentFolder.id)
#          else
          deleteFile(i)
        else
          deleteFolder(i)
    else
      if files[0].isDocument()
#        if files[0].paths && files[0].paths.length>1
#          removedFolderId=[]
#          folderIds = $('ul[data-id="'+files[0].id+'"] :checked')
#          for q in folderIds
#            removedFolderId.push(q.getAttribute('data-id'))
#          if removedFolderId.length==files[0].paths.length
#            deleteFile(files[0],files[0].paths.length)
#          else
#            for folderId in removedFolderId
#              removeFromFolder(files[0],folderId)
#        else
        deleteFile(files[0])
      else
        deleteFolder(files[0])
  $scope.isDisabled = ()->
    $scope.pathIsLoading

  $scope.ok = ()->
    totalDeleteCount(files)
    deleteController(files)
    $uibModalInstance.close($scope.folderName)
  $scope.cancel = ()->
    $uibModalInstance.dismiss('cancel')
.controller "createProgressBarModal", ($scope, $uibModalInstance ,rootScope, queueFiles,UploadQueue)->
#  expose a progressHandler we can close it by dismiss()
  rootScope.progressHandler=$uibModalInstance
  $scope.files = queueFiles
  $scope.isUploading = ()->
    UploadQueue.uploading
  $scope.isBarOpen = ()->
    UploadQueue.barIsOpen
  $scope.toggleQueue=()->
    $('#progress-bar').toggle(300)
    UploadQueue.barIsOpen = !UploadQueue.barIsOpen
    $scope.isBarOpen()
#    $scope.$apply()
#    return true can solve angular problem ,angularJS does not allow us manipulate dom directly,without this 'return true' it will call a throw error
#    return true
  $scope.ok=()->
  $scope.cancel=()->
    $uibModalInstance.dismiss()
    UploadQueue.queueFiles = []
    UploadQueue.modal=false
.controller "requestShareModal", ($scope, $uibModalInstance, file, ApiService)->
  $scope.loading=false
  $scope.ok=()->
    $scope.loading=true
    ApiService.syncCmisFileNameToCdrm(file,()->
      console.log('===syncFileName to cDRM succ')
    ,()->
      console.log('===syncFileName failed')
    )
    ApiService.requestForShare(file,(data)->
      $scope.loading=false
      console.log(data)
      Utils.success('申请成功')
      $uibModalInstance.dismiss()
    ,(err)->
      $scope.loading=false
      if err && err.message
        Utils.warning(err.message)
      else
        Utils.warning('申请失败，请稍后在试')
      $uibModalInstance.dismiss()
    )
  $scope.cancel=()->
    $uibModalInstance.dismiss()
.controller 'setCDRMPermCtrlNew', ($scope,Utils,$translate,parentScope,$timeout,$uibModalInstance,userData,$log,file,ApiService,defaultProtectTemplate,CmisService,dropFiles,justShowTemplate,userListArr,emailList,title)->
  $scope.title=title
  console.log('====setCDRMPermCtrl')
  # 该controller
  # 上传
  # 展示模版
  console.log(userData)
  console.log(file)
  console.log(emailList)
  $scope.pageCount=userData && userData.data && userData.data.pageCount || ''
#  $scope.pageCount=40
  if file && file.cDocId
    $scope.fileCdocId=file.cDocId
  # allUserList = enterprise user + enterpriseAllUser(group) + hasSetPermUserNotInEnterprise
  #  user data from server side stucture
  #    cas_id:"5b3ae541e4b098d865668e26"
  #    company_name:null
  #    created:"2018-07-03 02:54:17"
  #    email:"wnlufq54036@027168.com"  needed
  #    firstname:null
  #    full_name:"wnlufq54036"         needed
  #    id:"139"
  #    lastname:null
  #    user_type:"1"
  #  custom property
  #    isSetPerm:false 用户是否已经设置过权限 compareUserListWithhasSetPermUserList 函数设置
  #    isGroup:false   用户组

  userListEmailArr=[]
  if userListArr && userListArr.length>0
    for usr0 in userListArr
      userListEmailArr.push(usr0.email)

  if emailList[0] && emailList[0]['emailList'] && emailList[0]['emailList'].length>0
    for user in emailList[0]['emailList']
#      if user.emailName.indexOf(Utils.getEmailDomainFrom(CmisService.email))==-1
      if userListEmailArr.indexOf(user.emailName)==-1 && user.emailName!=CmisService.email
        userListArr.push({
          email:user.emailName
          full_name:user.emailName.split('@')[0]
        })

  $scope.allUserList=userListArr
  $scope.searchText=''
  ###
    数据 从两个数据源  一个是文档本身 一个是从模版  两个互相不交叉
    # defaultTemplateMode true 那么保存模版模式 用户点击完保存 需要执行上传文件操作 并且在文档转换完成之后 并且利用已有或者重新设置的模版设置 权限
    # defaultTemplateMode false 就是用户自行设置 文档权限
  ###

  $scope.justShowTemplate=justShowTemplate #仅仅有一个确认按钮 功能是用户查看策略

  $scope.defaultTemplateMode=defaultProtectTemplate
  $scope.customTemplateMode=false
  $scope.saveTemplate={
    checked:true
  }
  $scope.serverHasTemplate=false
  $scope.showDetail=false
  $scope.toggled = (open)->
    $log.log('Dropdown is now: ', open)

  # use template
  if $scope.defaultTemplateMode
# server has template
    if userData
      userAcl=userData.userList
      $scope.serverHasTemplate=true
    else
# server has no template   default template
      userAcl=[
        {
          "userEmail": ''
          "groupId": "",
          "isGroup": 0,
          "everyone": 0,
          "permitType": 3,
          "emailDomain": Utils.getEmailDomainFrom(CmisService.email)
          "permission": [
            0
          ],
          "offlineDays": 0,
          "deviceLimit": 0,
          "onlineDate": "",
          "fullControl": 0,
          "offline": 0,
          "online": 0,
          "onlineDays": 0,
          "accessPages": {
            "isAccessPages": 0,
            "wrapperContent": "You do not have permission to view this page",
            "wrapperPic": "",
            "Pages": []
          }
          "accessPagesStr":''
        }
      ]

# not template mode
  else
# 过滤掉 isRevoke 1

    userAcl=[]
    for acl in userData.data.acl
      if acl.isRevoke!=1
        userAcl.push(acl)
  #    userAcl=userData.data.acl

  $scope.codeMap={
    400:$translate.instant('Inserting, deleting, and rotating pages')
    100:$translate.instant('Filling in forms and signing existing signature fields')
    120:$translate.instant('Commenting, filling form, signing existing signature fields')
    128:$translate.instant('Any except extracting pages')
    200:$translate.instant('Text access for the visually impaired')
    210:$translate.instant('Any')
    4:$translate.instant('Low Resolution(150 dpi)')
    804:$translate.instant('High Resolution')
    0:$translate.instant('None')
  }

  # acl 返回的是类似 'Print'=>[800,4],'Edit'=>[8,20,100,400],'Copy'=>[10,200]
  # 需要把 对应的 权限加起来

  editPermCodes=[400,100,120,128]
  copyPermCodes=[200,210]
  printPermCodes=[4,804]
  addPermArr=(permArr)->
    # in [4,800,20,100,200]
    # out [804,120,200]
    Print=[800,4]
    Edit=[8,20,100,400]
    Copy=[10,200]
    arr=[]
    editPerm=0
    copyPerm=0
    printPerm=0
    for perm in permArr
      if Edit.indexOf(parseInt(perm))>-1
        editPerm+=parseInt(perm)
      if Copy.indexOf(parseInt(perm))>-1
        copyPerm+=parseInt(perm)
      if Print.indexOf(parseInt(perm))>-1
        printPerm+=parseInt(perm)
    arr.push(editPerm)
    arr.push(copyPerm)
    arr.push(printPerm)
    arr

  #  test data
  #  userAcl=[
  #    {userAttribute:{userEmail:'anyone'},selected:false,isValidInput:true},
  #    {userAttribute:{userEmail:'123@qq.com'},selected:false,isValidInput:true},
  #    {userAttribute:{userEmail:'321@qq.com'},selected:false,isValidInput:true}
  #  ]
  $scope.customizeProtectTemplate=()->
    $scope.customTemplateMode=true
  decodePerm=(permissionCodeArr)->
#    console.log('===before permissionCodeArr',permissionCodeArr)
    if !justShowTemplate
       permissionCodeArr=addPermArr(permissionCodeArr)
#    console.log('===after permissionCodeArr',permissionCodeArr)
    data={
      copyCode:0
      editCode:0
      printCode:0
    }
    if permissionCodeArr&&permissionCodeArr.length>0
      for code in permissionCodeArr
        if parseInt(code) in copyPermCodes
          data.copyCode=parseInt(code)
      for code1 in permissionCodeArr
        if parseInt(code1) in editPermCodes
          data.editCode=parseInt(code1)
      for code2 in permissionCodeArr
        if parseInt(code2) in printPermCodes
          data.printCode=parseInt(code2)
    console.log('---',data)
    return data

  $scope.users=[]
  # init enterpriseAllUsers and anyone users
  initEnterpriseAndAnyoneUser=()->
    $scope.enterpriseAllUsers={
      name:''
      selected:false
      isValidInput:true
      drmMsgId:''
      permitType: 3
      emailDomain:Utils.getEmailDomainFrom(CmisService.email)
      everyone:1
      groupID:''
      groupName:''
      isGroup:0
      accessPagesStr:''
      permissions:[0,0,0]
      offline:0
      offlineDuration:0
      online:0
      onlineDate:0
      onlineDays:0
      deviceLimit:0
      permData:decodePerm([0])
      readPerm:"0"
      readPermOrigin:"0"
    }
    $scope.anyoneUser={
      name:''
      selected:false
      isValidInput:true
      drmMsgId:''
      permitType: 4
      emailDomain:''
      everyone:1
      groupID:''
      groupName:''
      isGroup:0
      permissions:[0,0,0]
      offline:0
      offlineDuration:0
      online:0
      onlineDate:0
      onlineDays:0
      deviceLimit:0
      permData:decodePerm([0])
      readPerm:"0"
      readPermOrigin:"0"
      accessPagesStr:''
    }
  transcode = (pages) ->
    pagesStr = ''
    if pages.length > 0
      i = 0
      while i < pages.length
        if $.isArray(pages[i])
          pages.splice i, 1, pages[i].join('-')
        i++
      pagesStr = pages.join(',')
    pagesStr

  formatCdrmUserDate=()->
    initEnterpriseAndAnyoneUser()
    console.log('=== user data from server ')
    console.log(userAcl)
    for acl in userAcl
      user={
        name:acl.userAttribute && acl.userAttribute.userEmail || acl.userEmail
        selected:false
        isValidInput:true
        drmMsgId:acl._id||''
        permitType: acl.permitType
        emailDomain:acl.userAttribute && acl.userAttribute.Domain || acl.emailDomain  || ''
        full_name:acl.userAttribute && acl.userAttribute.userName || ''
        everyone:acl.everyone||0
        groupID:acl.groupID||''
        groupName:acl.groupName||''
        isGroup:acl.isGroup||0
        permissions:acl.permissions||acl.permission||[0,0,0]
        offline:acl.offline||0
        offlineDuration:acl.offlineDuration||0
        online:acl.online||0
        onlineDate:acl.onlineDuration||acl.onlineDate||''
        onlineDays:acl.onlineDurationDays||acl.onlineDays||0
        deviceLimit:acl.deviceLimit && acl.deviceLimit.limitNum? && acl.deviceLimit.limitNum+'' || acl.deviceLimit
        permData:decodePerm(acl.permissions||acl.permission)
        readPerm:acl.accessPages && acl.accessPages.isAccessPages && parseInt(acl.accessPages.isAccessPages)==1 && "2" || "1"
        readPermOrigin:acl.accessPages && acl.accessPages.isAccessPages && parseInt(acl.accessPages.isAccessPages)==1 && "2" || "1"
        accessPages: {
          "isAccessPages": acl.accessPages && acl.accessPages.isAccessPages || 0
          "wrapperContent": acl.accessPages && acl.accessPages.wrapperContent || "You do not have permission to view this page"
          "wrapperPic": acl.accessPages && acl.accessPages.wrapperPic || ""
          "Pages": acl.accessPages && acl.accessPages.Pages  || []
        }
        accessPagesStr:transcode(acl.accessPages && acl.accessPages.Pages)
      }
      # enter prise user any one user not put into user list
      # neet special

      if user.emailDomain
        user.name=$translate.instant('enterprise_all_users')
        $scope.enterpriseAllUsers=user
      else if parseInt(user.everyone)==1
        console.log('ddd')
        $scope.anyoneUser=user
      else
        $scope.users.push(user)
    console.log('---anyone',$scope.anyoneUser)
    console.log('---enterprise ',$scope.enterpriseAllUsers)
    console.log('----init scope users',$scope.users)
  formatCdrmUserDate()
  # 待选区 需要和已选区 对比   已选的需要给出表示
  compareUserListWithHasSetPermUserList=()->
    emailArr=[]
    for user in $scope.users
      emailArr.push(user.name)
    for user1 in $scope.allUserList
      user1.isSetPerm=false
    for user0 in $scope.allUserList
      if emailArr.indexOf(user0.email)>-1
        user0.isSetPerm=true
    console.log('===$scope.allUserList')
    console.log($scope.allUserList)
  compareUserListWithHasSetPermUserList()
  $scope.toggleTemplateDetail=()->
    $scope.showDetail=!$scope.showDetail
  $scope.chooseUser=(user,e)->
    if e
      e.stopPropagation()
    if user=='anyone'
      $scope.currentUser=$scope.anyoneUser
    else if user=='enterpriseAllUsers'
      $scope.currentUser=$scope.enterpriseAllUsers
    else
      $scope.currentUser=user

    for originUser in $scope.users
      originUser.selected=false
    $scope.enterpriseAllUsers && $scope.enterpriseAllUsers.selected=false
    $scope.anyoneUser && $scope.anyoneUser.selected=false
    $scope.currentUser && $scope.currentUser.selected=true
    console.log('curUser----',$scope.currentUser)
#    $scope.choseUsersArr=[]
#    $scope.choseUsersArr.push(user)

  $scope.placeholder=$translate.instant('enter_email_address')
  $scope.choseUsersArr=[]

  console.log($scope.defaultProtectTemplate)
  if $scope.defaultTemplateMode
    $scope.chooseUser($scope.enterpriseAllUsers)

#    $scope.curChooseUser=$scope.users[0]
#    $scope.curChooseUser.selected=true
#    $timeout(()->
#      $scope.$apply()
#    ,0)
  else
    $scope.chooseUser($scope.enterpriseAllUsers)
  
  $scope.changeOnlineType=(type)->
    console.log('-----changeOnlineType')
    console.log($scope.currentUser)
    if $scope.currentUser
      $scope.currentUser.online=type
  $scope.changeOfflineType=(type)->
    console.log('-----changeOfflineType')
    console.log($scope.currentUser)
    if $scope.currentUser
      $scope.currentUser.offline=type
  $scope.changeDeviceLimit=(limitNum)->

#    if parseInt($scope.currentUser.deviceLimit)!=0 && limitNum==3
#      return
    console.log('-----changeDeviceLimit')
    console.log($scope.currentUser)
    if $scope.currentUser
#      if parseInt($scope.currentUser.deviceLimit)!=0
#        $scope.currentUser.deviceLimit=$scope.currentUser.deviceLimit
#      else
        $scope.currentUser.deviceLimit=limitNum
  deleteUser=(user)->

    # 删除 everyone 和 enterpriseAllusers
    if parseInt(user.everyone)==1 || user.emailDomain
      user.drmMsgId=''
      user.readPerm='0'
      return

    # search delete can not use index
    for usrObj,index in $scope.users
      console.log(usrObj)
      if usrObj.name==user.name
        deleteUserIndex=index
    if !deleteUserIndex?
      return
    $scope.users.splice(deleteUserIndex,1)
    hasSelectedFile=false
    for user0 in $scope.users
      if user0.selected==true
        hasSelectedFile=true
    if !hasSelectedFile
      $scope.currentUser=null
    # 删除完选中 企业用户
    $scope.chooseUser($scope.enterpriseAllUsers)
    compareUserListWithHasSetPermUserList()
    if $scope.choseUsersArr.length>0
      for index1,user1 of $scope.choseUsersArr
        if user1.name == user.name
          $scope.choseUsersArr.splice(index1,1)
  $scope.setReadPerm=(user,originReadPerm)->
    # originReadPerm 说明用户点击了取消 还原回 之前的 readPerm
    if originReadPerm
      user.readPerm=user.readPermOrigin
    else
      user.readPermOrigin=user.readPerm
      if parseInt(user.readPerm)==2
        # 如果是 accessPage 选中 不允许编辑权限
        user.permData.copyCode=0
        user.permData.editCode=0
        user.permData.printCode=0

    console.log(user)

  $scope.setRead=(user)->
    if parseInt(user.readPerm)==1
      user.readPerm='0'
    else
      user.readPerm='1'
      user.readPermOrigin='1'


  $scope.setReadPermTo=(user,fromCheckbox)->
    # user.readPerm 是已经改变了
    # user.readPermOrigin 还没有改变
    # 用户cancel需要还原成之前的readPerm
    if fromCheckbox
      $scope.setRead(user)
    if user.drmMsgId
      # 数据是服务器返回的
      # confirm to delete
      if parseInt(user.readPerm)==0
        $translate('cDrm_perm_delete_confirm').then (text)->
          Utils.confirm text,'','','', ()->
            Utils.showLoading()
            ApiService.deleteUserPermInCDrm(user.drmMsgId,file.cDocId,()->
              Utils.success('删除成功')
              Utils.closeLoading()
              deleteUser(user)
            ,()->
              $scope.setReadPerm(user)
              Utils.closeLoading()
              Utils.warning('删除失败，请稍后在试')
            )
          ,()->
            console.log('user cancel')
            # 还原
            $scope.setReadPerm(user,true)
      if parseInt(user.readPerm)==2
        $translate('page_access_warning').then (text)->
          Utils.confirm text,'','','', ()->
            console.log('user confirm')
            $scope.setReadPerm(user)
          ,()->
            console.log('user cancel')
            # 还原
            $scope.setReadPerm(user,true)
    else
      console.log(user)
      if parseInt(user.readPerm)==0
        $translate('cDrm_perm_delete_confirm').then (text)->
          Utils.confirm text,'','','', ()->
            deleteUser(user)
          ,()->
            console.log('user cancel')
            # 还原
            $scope.setReadPerm(user,true)
      if parseInt(user.readPerm)==2
        $translate('page_access_warning').then (text)->
          Utils.confirm text,'','','', ()->
            console.log('user confirm')
            $scope.setReadPerm(user)
          ,()->
            console.log('user cancel')
            # 还原
            $scope.setReadPerm(user,true)
#      if user.readPerm=='0'
#        user.readPerm='1'
#      else
#        user.readPerm='0'



  $scope.deleteUser=(user)->
    if user.drmMsgId
      # 数据是服务器返回的
      # confirm to delete
      $translate('cDrm_perm_delete_confirm').then (text)->
        Utils.confirm text,'','','', ()->
          Utils.showLoading()
          ApiService.deleteUserPermInCDrm(user.drmMsgId,file.cDocId,()->
            Utils.success('删除成功')
            Utils.closeLoading()
            deleteUser(user)
          ,()->
            Utils.closeLoading()
            Utils.warning('删除失败，请稍后在试')
          )
    else
      $translate('cDrm_perm_delete_confirm').then (text)->
        Utils.confirm text,'','','', ()->
          deleteUser(user)

  $scope.addUser=()->
    $scope.users.push({
      name:Date.now(),
      selected:false
    })

  $scope.checkIfValid=()->
    Utils.rebound('check-valid',()->
      console.log('=======')
      valid = checkAccessPages($scope.currentUser)
      if valid && valid.length>0
        $scope.currentUser.errInput=false
        $scope.currentUser.errMsg=''
      else
        $scope.currentUser.errInput=true
      console.log($scope.currentUser)
      console.log(valid)
    ,500)
  checkAccessPages =(user)->
    console.log('====test ')
    allowPage = if user.accessPagesStr.length == 0 then false else user.accessPagesStr
    tempArray = []
    if allowPage != false and allowPage != undefined
      tempArray = allowPage.split(/[,;，；\s]\s*/)
      if tempArray.length > 0
        pageCount = 99999
        i = 0
        while i < tempArray.length
          if parseInt(tempArray[i]) == 0 or parseInt(tempArray[i]) > pageCount or !/^\d+$/.test(tempArray[i]) and !/^(\d+)-(\d+)$/.test(tempArray[i])
            user.errMsg=$translate.instant('cannot_exceed_page_count')
            return false
          str = tempArray[i].match(/\d+/g)
          rang = if tempArray[i].indexOf('-') != -1 then tempArray[i].split('-') else []
          if rang.length > 0
            max = Math.max.apply(null, rang)
            if max > pageCount
              user.errMsg=$translate.instant('cannot_exceed_page_count')
              return false
            tempArray.splice i, 1, rang
          else
            tempArray.splice i, 1, parseInt(tempArray[i])
          i++
      else if allowPage == 0 or !/^\d+$/.test(allowPage)
        $('#allowPage').val ''
        user.errMsg=$translate.instant('cannot_exceed_page_count')
        return false
      else
        allowPage = parseInt(allowPage)
        tempArray = [ allowPage ]
    console.log('======tempArray')
    console.log(tempArray)
    tempArray

  generatePostUserListData=(templateData)->
    # templateData 是不可以保存 页码信息的  因为 pdf 页码不同
    users=angular.copy($scope.users)
    users.push($scope.enterpriseAllUsers)
    users.push($scope.anyoneUser)
    console.log('==== users data before post')
    console.log(users)
    userList=[]
    for user in users
      # 过滤错误信息
      if user.isValidInput && (parseInt(user.readPerm)==1 || parseInt(user.readPerm)==2)
        permissionArr=[]
        permissionArr.push(user.permData.copyCode)
        permissionArr.push(user.permData.editCode)
        permissionArr.push(user.permData.printCode)

        userData={
          "userEmail": Utils.isValidEmail(user.name)&&user.name || '',
          "emailDomain": user.emailDomain || '',
          "isGroup":user.isGroup
          "everyone":user.everyone||0
          "permitType": "1",
          "fullControl": "0",
          "permission": permissionArr.length>0&&permissionArr||[0,0,0]
          "offline": user.offline
          "offlineDays": user.offlineDuration
          "online": user.online
          "deviceLimit": user.deviceLimit,
        }
        # 模版data 里面不能有页码信息
#        if !templateData
        userData['accessPages']={
          "isAccessPages": if parseInt(user.readPerm)==2 then 1 else 0,
          "wrapperContent": "",
          "wrapperPic": "",
          "Pages": checkAccessPages(user)
        }
        userData["accessPagesStr"]=user.accessPagesStr
        # "online": user.online
        # "onlineDays": user.onlineDays
        # "onlineDate": user.onlineDate
        # emailDomain 企业所有用户
        if user.emailDomain
          userData.permitType=3
        else if parseInt(user.everyone)==1
          userData.permitType=4
        else
          userData["groupId"]=user.groupId
        if user.online==2
          userData.onlineDate=user.onlineDate
        else if user.online==1
          userData.onlineDays=user.onlineDays
        else
          userData.onlineDays=0
        userList.push(userData)
    console.log('=====post userList ')
    console.log(userList)
    userList

  # 这个是从左侧加到右侧 使用的
  generateUser=(email,emailDomain,fullName)->
    # emailDomain 特殊处理
    if emailDomain
      return {
        name:$translate.instant('enterprise_all_users')
        isValidInput:true
        avatar:''
        selected:false
        full_name:fullName
        emailDomain:Utils.getEmailDomainFrom(CmisService.email)
        groupID:''
        groupName:''
        isGroup: 0
        permissions:[0,0,0]
        deviceLimit:0
        offline:0
        offlineDuration:0
        online:0
        onlineDays: ''
        onlineDate:''
        readPerm:"1"
        accessPagesStr:''
        readPermOrigin:"1"
        permData:{
          copyCode:0
          editCode:0
          printCode:0
        }
      }
    # email not only email maybe group name
    for user in $scope.users
      if user.name==email
        return
    # online:0  never
    # online:1  days
    # online:2  specific date
    return {
      name:email
      isValidInput:Utils.isValidEmail(email) || Utils.isInGroup(email)
      avatar:email
      emailDomain:''
      full_name:fullName
      accessPagesStr:''
      selected:false
      groupID:''
      groupName:''
      isGroup: 0
      permissions:[0,0,0]
      deviceLimit:0
      offline:0
      offlineDuration:0
      online:0
      onlineDays: ''
      onlineDate:''
      readPerm:"1"
      readPermOrigin:"1"
      permData:{
        copyCode:0
        editCode:0
        printCode:0
      }
    }
  $scope.handleKeyUp=(e)->
    console.log(e)
    e && e.stopPropagation()
    Utils.rebound('keypress',()->
      # 连续输入只处理最后一次
      valid=false
      valid=Utils.isValidEmail($scope.searchText)
      for user in $scope.allUserList
        if $scope.searchText==user.email
          valid=false
      if $scope.searchText==CmisService.email
        valid=false
      $scope.isValidInput=valid
      console.log('====is valid input',$scope.isValidInput)
    ,300)
  $scope.clearInput=(key)->
    $scope[key]=''
    $scope.isValidInput=false


  $scope.addNewUser=(user,userInput)->
    if userInput
      if !Utils.isValidEmail(userInput)
        Utils.warning($translate('invalid_email',{email:userInput}))
        return
      else
        ApiService.createUserRelationship($scope.searchText)
        user = generateUser($scope.searchText)
        $scope.users.push(user)
        $scope.chooseUser(user)
        $scope.searchText=''
    else
      # user already in targetArr
      for user0 in $scope.users
        if user0.name==user.email
          $scope.chooseUser(user0)
          return
      if user.isGroup
        return $scope.addEnterpriseAllUsers()
      else
        theuser = generateUser(user.email,null,user.full_name)
        $scope.users.push(theuser)
        $scope.chooseUser(theuser)
        console.log('====end users')
        console.log($scope.users)
    compareUserListWithHasSetPermUserList()
  $scope.addEnterpriseAllUsers=()->
    console.log('------11')
    console.log($scope.users)
    $scope.users=[]
    $scope.choseUsersArr=[]
    $scope.currentUser=null
    enterpriseUser=generateUser(null,true)
    $scope.users.push(enterpriseUser)
    $scope.chooseUser(enterpriseUser)
    compareUserListWithHasSetPermUserList()
  # date picker part
  $scope.today =()->
    $scope.dt=new Date()
  $scope.today();
  $scope.clear = ()->
    $scope.dt=null
  $scope.inlineOptions={
    customClass: getDayClass,
    minDate: new Date(),
    showWeeks: true
  }
  $scope.dateOptions={
    dateDisabled: disabled,
    formatYear: 'yy',
    maxDate: new Date(2020, 5, 22),
    minDate: new Date(),
    startingDay: 1
  }
  # Disable weekend selection
  disabled=(data)->
    date = data.date
    mode = data.mode
    return mode == 'day' && (date.getDay() == 0 || date.getDay() == 6);
  $scope.toggleMin=()->
    $scope.inlineOptions.minDate = if $scope.inlineOptions.minDate then null else new Date();
    $scope.dateOptions.minDate = $scope.inlineOptions.minDate
  $scope.toggleMin();
  $scope.open1=()->
    $scope.popup1.opened = true
  $scope.open2 =()->
    $scope.popup2.opened = true
  $scope.setDate=(year, month, day)->
    $scope.dt = new Date(year, month, day)

  $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']
  $scope.format = $scope.formats[0];
  $scope.altInputFormats = ['M!/d!/yyyy']

  $scope.popup1 = {
    opened: false
  }
  $scope.popup2 = {
    opened: false
  }
  tomorrow = new Date()
  tomorrow.setDate(tomorrow.getDate() + 1)
  afterTomorrow = new Date()
  afterTomorrow.setDate(tomorrow.getDate() + 1)
  $scope.events = [
    {
      date: tomorrow,
      status: 'full'
    },
    {
      date: afterTomorrow,
      status: 'partially'
    }
  ]
  getDayClass=(data)->
    date = data.date
    mode = data.mode
    if mode == 'day'
      dayToCheck = new Date(date).setHours(0,0,0,0)
      for i in $scope.events
        currentDay = new Date(i.date).setHours(0,0,0,0)
        if (dayToCheck == currentDay)
          return $scope.events[i].status
    return ''
  # time picker
  $scope.mytime = new Date();
  $scope.hstep = 1;
  $scope.mstep = 1;
  $scope.options = {
    hstep: [1, 2, 3],
    mstep: [1, 5, 10, 15, 25, 30]
  };
  $scope.ismeridian = false;
  $scope.toggleMode=()->
    $scope.ismeridian = ! $scope.ismeridian
  $scope.update =()->
    d = new Date();
    d.setHours(14)
    d.setMinutes(0)
    $scope.mytime=d
  $scope.changed=()->
    $log.log('Time changed to: ' + $scope.mytime)
  $scope.clear=()->
    $scope.mytime = null

  $scope.updateTemplate=()->
    userList=generatePostUserListData(true)
    console.log('===== userList ')
    console.log(userList)
    if userList.length==0
      warningMsg=$translate.instant('user_list_blank')
      Utils.warning(warningMsg)
      return
    for user in userList
      if user.onlineDate
        if !$scope.pattern.test(user.onlineDate)
          Utils.warning("日期输入不符合2020-01-01 09:00:00")
          return

    $scope.loading=true
    postTemplateData={
      "templateName": "Default Template",
      "notice": "0",
      "uploadFile": "0",
      "invitation": "0",
      "userList": userList
    }
    console.log('=====postTemplateData')
    console.log(postTemplateData)
    # save templateData to Utils
    Utils.templateData=postTemplateData
    if $scope.serverHasTemplate
      ApiService.updateProtectTemplate(postTemplateData,(data,scope)->
        console.log('---succ')
        Utils.success($translate.instant('Save Template Success'))
        if data && data.code==100000
          if data.data && data.data.length && data.data[0]
            Utils.templateData=data.data[0]
      ,(data)->
        Utils.warning(data.message)
      )
    else
      ApiService.addProtectTemplate(postTemplateData,(data,scope)->
        console.log('---succ')
        Utils.success($translate.instant('Save Template Success'))
        if data && data.code==100000
          if data.data && data.data.length && data.data[0]
            Utils.templateData=data.data[0]
      ,(data)->
        Utils.warning(data.message)
      )

  $scope.pattern=/\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}/g
  $scope.ok=()->
# 日期格式
#    $scope.$broadcast('protect')
    console.log($scope.users)
    userList=generatePostUserListData()

    console.log('====post Form Data ',userList)


#     if !templateData
    #          userData['accessPages']={
    #            "isAccessPages": if parseInt(user.readPerm)==2 then 1 else 0,
    #            "wrapperContent": "",
    #            "wrapperPic": "",
    #            "Pages": checkAccessPages(user)
    #          }
    #          userData["accessPagesStr"]=user.accessPagesStr

#    return false
#    return false
#    if userList.length==0
#      warningMsg=$translate.instant('user_list_blank')
#      Utils.warning(warningMsg)
#      $uibModalInstance.close()
#      return
    for user in userList
      if user.onlineDate
        if !$scope.pattern.test(user.onlineDate)
          Utils.warning("日期输入不符合2020-01-01 09:00:00")
          return
      if user.accessPages && user.accessPages['isAccessPages'] && parseInt(user.accessPages['isAccessPages'])==1
        if !user.accessPages['Pages'] || user.accessPages['Pages'].length==0
          email=''
          if user.userEmail
            email=user.userEmail
          else if parseInt(user.everyone)==1
            email=$translate.instant('anyone')
          else
            email=$translate.instant('enterprise_all_users')
          Utils.warning($translate.instant('cannot_exceed_page_count',{email:email}))
          return
    $scope.loading=true

    postTemplateData={
      "templateName": "Default Template",
      "notice": "0",
      "uploadFile": "0",
      "invitation": "0",
      "userList": userList
    }
    console.log('=====postTemplateData')
    console.log(postTemplateData)
    # save templateData to Utils
    Utils.templateData=postTemplateData

    if !$scope.defaultTemplateMode
      postData={
        "cDocID": file.cDocId
        "fileLink": "",
        "notice": "0",
        "invitation": "0",
        "userList": userList
      }
      console.log('====postData====')
      console.log(postData)
      if userList.length>0
        Utils.showLoading()
        ApiService.setCdrmPermission(postData,(data)->
          console.log('---succ')
          $scope.loading=false
          Utils.closeLoading()
          $uibModalInstance.close()
          if data && data.ret==0
            Utils.success($translate.instant('set_perm_succ'))
        ,(data)->
          $scope.loading=false
          Utils.warning(data.message)
          Utils.closeLoading()
          $uibModalInstance.close()
        )
      else
        $uibModalInstance.close()
    else
      $uibModalInstance.close()
      if dropFiles
        parentScope.upload(dropFiles)
      else
        if !justShowTemplate
          parentScope.openUploadFilePicker()


  $scope.cancel=()->
#    $scope.defaultProtectTemplate=!$scope.defaultProtectTemplate
    $uibModalInstance.close()


.controller 'setCDRMPermCtrl', ($scope,Utils,$translate,parentScope,$timeout,$uibModalInstance,userData,$log,file,ApiService,defaultProtectTemplate,CmisService,dropFiles,justShowTemplate)->
  console.log('====setCDRMPermCtrl')
  console.log(userData)
  console.log(file)
  if file && file.cDocId
    $scope.fileCdocId=file.cDocId

  ###
    数据 从两个数据源  一个是文档本身 一个是从模版  两个互相不交叉
    # defaultTemplateMode true 那么保存模版模式 用户点击完保存 需要执行上传文件操作 并且在文档转换完成之后 并且利用已有或者重新设置的模版设置 权限
    # defaultTemplateMode false 就是用户自行设置 文档权限
  ###
#  $scope.pageCount=userData && userData.data && userData.data.pageCount || 0
  $scope.pageCount=40
  $scope.justShowTemplate=justShowTemplate #仅仅有一个确认按钮 功能是用户查看策略

  $scope.defaultTemplateMode=defaultProtectTemplate
  $scope.customTemplateMode=false
  $scope.saveTemplate={
    checked:true
  }
  $scope.serverHasTemplate=false
  $scope.showDetail=false
  $scope.toggled = (open)->
    $log.log('Dropdown is now: ', open)

  # use template
  if $scope.defaultTemplateMode
    # server has template
    if userData
      userAcl=userData.userList
      $scope.serverHasTemplate=true
    else
    # server has no template   default template
      userAcl=[
        {
          "userEmail": CmisService.email
          "groupId": "",
          "isGroup": 0,
          "everyone": 0,
          "permitType": 1,
          "emailDomain": Utils.getEmailDomainFrom(CmisService.email)
          "permission": [
            0
          ],
          "offlineDays": 0,
          "deviceLimit": 0,
          "onlineDate": "",
          "fullControl": 0,
          "offline": 0,
          "online": 0,
          "onlineDays": 0,
          "accessPages": {
            "isAccessPages": 0,
            "wrapperContent": "",
            "wrapperPic": "",
            "Pages": []
          }
        }
      ]

  # not template mode
  else
    # 过滤掉 isRevoke 1

    userAcl=[]
    for acl in userData.data.acl
      if acl.isRevoke!=1
        userAcl.push(acl)
#    userAcl=userData.data.acl

  $scope.codeMap={
    400:$translate.instant('Inserting, deleting, and rotating pages')
    100:$translate.instant('Filling in forms and signing existing signature fields')
    120:$translate.instant('Commenting, filling form, signing existing signature fields')
    128:$translate.instant('Any except extracting pages')
    200:$translate.instant('Text access for the visually impaired')
    210:$translate.instant('Any')
    4:$translate.instant('Low Resolution(150 dpi)')
    804:$translate.instant('High Resolution')
    0:$translate.instant('None')
  }

  # acl 返回的是类似 'Print'=>[800,4],'Edit'=>[8,20,100,400],'Copy'=>[10,200]
  # 需要把 对应的 权限加起来

  editPermCodes=[400,100,120,128]
  copyPermCodes=[200,210]
  printPermCodes=[4,804]
  addPermArr=(PermArr)->
    # in [4,800,20,100,200]
    # out [804,120,200]
    arr=[]
    editPerm=0
    copyPerm=0
    printPerm=0
    for perm in permArr
      if editPermCodes.indexOf(parseInt(perm))>-1
        editPerm+=parseInt(perm)
      if copyPermCodes.indexOf(parseInt(perm))>-1
        copyPerm+=parseInt(perm)
      if printPermCodes.indexOf(parseInt(perm))>-1
        printPerm+=parseInt(perm)
    arr.push(editPerm,copyPerm,printPerm)
    arr

#  test data
#  userAcl=[
#    {userAttribute:{userEmail:'anyone'},selected:false,isValidInput:true},
#    {userAttribute:{userEmail:'123@qq.com'},selected:false,isValidInput:true},
#    {userAttribute:{userEmail:'321@qq.com'},selected:false,isValidInput:true}
#  ]
  $scope.customizeProtectTemplate=()->
    $scope.customTemplateMode=true

  decodePerm=(permissionCodeArr)->
    console.log('===before permissionCodeArr',permissionCodeArr)
    if !justShowTemplate
      permissionCodeArr=addPermArr(permissionCodeArr)
    console.log('===after permissionCodeArr',permissionCodeArr)
    data={
      copyCode:0
      editCode:0
      printCode:0
    }

    if permissionCodeArr&&permissionCodeArr.length>0
      for code in permissionCodeArr
        if parseInt(code) in copyPermCodes
          data.copyCode=parseInt(code)
      for code1 in permissionCodeArr
        if parseInt(code1) in editPermCodes
          data.editCode=parseInt(code1)
      for code2 in permissionCodeArr
        if parseInt(code2) in printPermCodes
          data.printCode=parseInt(code2)
    console.log('---',data)
    return data

  $scope.users=[]
  formatCdrmUserDate=()->
    console.log('=== user data from server ')
    console.log(userAcl)
    for acl in userAcl
      user={
        name:acl.userAttribute && acl.userAttribute.userEmail || acl.userEmail
        selected:false
        isValidInput:true
        drmMsgId:acl._id||''
        permitType: acl.permitType
        emailDomain:acl.userAttribute && acl.userAttribute.Domain || acl.emailDomain  || ''
        everyone:acl.everyone||0
        groupID:acl.groupID||''
        groupName:acl.groupName||''
        isGroup:acl.isGroup||0
        permissions:acl.permissions||acl.permission||[0,0,0]
        online:acl.online||0
        onlineDate:acl.onlineDuration||acl.onlineDate||''
        onlineDays:acl.onlineDurationDays||acl.onlineDays||0
        permData:decodePerm(acl.permissions||acl.permission)
      }
      if user.emailDomain
        user.name='企业所有用户'
      $scope.users.push(user)
    console.log('----init users',$scope.users)
  formatCdrmUserDate()

  $scope.toggleTemplateDetail=()->
    $scope.showDetail=!$scope.showDetail
  $scope.chooseUser=(user,e)->
    if e
      e.stopPropagation()
    $scope.curChooseUser=user
    console.log('curUser----',$scope.curChooseUser)
    for originUser in $scope.users
      originUser.selected=false
    user.selected=true
    $scope.choseUsersArr=[]
    $scope.choseUsersArr.push(user)



  $scope.placeholder=$translate.instant('enter_email_address')
  $scope.choseUsersArr=[]

  console.log($scope.defaultProtectTemplate)
  if $scope.defaultTemplateMode
    $scope.chooseUser($scope.users[0])

#    $scope.curChooseUser=$scope.users[0]
#    $scope.curChooseUser.selected=true
#    $timeout(()->
#      $scope.$apply()
#    ,0)
  else
    $scope.curChooseUser=null

  $scope.changeOnlineType=(type)->
    console.log('-----dsadsa')
    console.log($scope.curChooseUser)
    if $scope.curChooseUser
      $scope.curChooseUser.online=type


  $scope.addUser=()->
    $scope.users.push({
      name:Date.now(),
      selected:false
    })
  generatePostUserListData=()->
    userList=[]
    for user in $scope.users
      # 过滤错误信息
      if user.isValidInput
        permissionArr=[]
        permissionArr.push(user.permData.copyCode)
        permissionArr.push(user.permData.editCode)
        permissionArr.push(user.permData.printCode)

        userDate={
          "userEmail": Utils.isValidEmail(user.name)&&user.name || '',
          "emailDomain": user.emailDomain || '',
          "isGroup":user.isGroup
          "permitType": "1",
          "fullControl": "0",
          "permission": permissionArr.length>0&&permissionArr||[0,0,0]
          "offline": "0",
          "offlineDays": 0,
          "online": user.online
          "deviceLimit": "0",
          "accessPages": {
            "isAccessPages": "0",
            "wrapperContent": "",
            "wrapperPic": "",
            "Pages": [
              0
            ]
          }
        }
        # "online": user.online
        # "onlineDays": user.onlineDays
        # "onlineDate": user.onlineDate
        if user.emailDomain
          userDate.permitType=3
        else
          userDate["groupId"]=user.groupId
        if user.online==2
          userDate.onlineDate=user.onlineDate
        else if user.online==1
          userDate.onlineDays=user.onlineDays
        else
          userDate.onlineDays=0
        userList.push(userDate)
    userList

  # date picker part
  $scope.today =()->
    $scope.dt=new Date()
  $scope.today();
  $scope.clear = ()->
    $scope.dt=null
  $scope.inlineOptions={
    customClass: getDayClass,
    minDate: new Date(),
    showWeeks: true
  }
  $scope.dateOptions={
    dateDisabled: disabled,
    formatYear: 'yy',
    maxDate: new Date(2020, 5, 22),
    minDate: new Date(),
    startingDay: 1
  }
  # Disable weekend selection
  disabled=(data)->
    date = data.date
    mode = data.mode
    return mode == 'day' && (date.getDay() == 0 || date.getDay() == 6);
  $scope.toggleMin=()->
    $scope.inlineOptions.minDate = if $scope.inlineOptions.minDate then null else new Date();
    $scope.dateOptions.minDate = $scope.inlineOptions.minDate
  $scope.toggleMin();
  $scope.open1=()->
    $scope.popup1.opened = true
  $scope.open2 =()->
    $scope.popup2.opened = true
  $scope.setDate=(year, month, day)->
    $scope.dt = new Date(year, month, day)

  $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']
  $scope.format = $scope.formats[0];
  $scope.altInputFormats = ['M!/d!/yyyy']

  $scope.popup1 = {
    opened: false
  }
  $scope.popup2 = {
    opened: false
  }
  tomorrow = new Date()
  tomorrow.setDate(tomorrow.getDate() + 1)
  afterTomorrow = new Date()
  afterTomorrow.setDate(tomorrow.getDate() + 1)
  $scope.events = [
    {
      date: tomorrow,
      status: 'full'
    },
    {
      date: afterTomorrow,
      status: 'partially'
    }
  ]
  getDayClass=(data)->
    date = data.date
    mode = data.mode
    if mode == 'day'
      dayToCheck = new Date(date).setHours(0,0,0,0)
      for i in $scope.events
        currentDay = new Date(i.date).setHours(0,0,0,0)
        if (dayToCheck == currentDay)
          return $scope.events[i].status
    return ''
  # time picker
  $scope.mytime = new Date();
  $scope.hstep = 1;
  $scope.mstep = 1;
  $scope.options = {
    hstep: [1, 2, 3],
    mstep: [1, 5, 10, 15, 25, 30]
  };
  $scope.ismeridian = false;
  $scope.toggleMode=()->
    $scope.ismeridian = ! $scope.ismeridian
  $scope.update =()->
    d = new Date();
    d.setHours(14)
    d.setMinutes(0)
    $scope.mytime=d
  $scope.changed=()->
    $log.log('Time changed to: ' + $scope.mytime)
  $scope.clear=()->
    $scope.mytime = null

  $scope.pattern=/\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}/g
  $scope.ok=()->
    # 日期格式
    $scope.$broadcast('protect')
    console.log($scope.users)
    userList=generatePostUserListData($scope.users)
    if userList.length==0
      warningMsg=$translate.instant('user_list_blank')
      Utils.warning(warningMsg)
      return
    for user in userList
      if user.onlineDate
        if !$scope.pattern.test(user.onlineDate)
          Utils.warning("日期输入不符合2020-01-01 09:00:00")
          return

    $scope.loading=true
    postTemplateData={
      "templateName": "Default Template",
      "notice": "0",
      "uploadFile": "0",
      "invitation": "0",
      "userList": userList
    }
    console.log('=====postTemplateData')
    console.log(postTemplateData)
    # save templateData to Utils
    Utils.templateData=postTemplateData

    # 保存模版的请求 由用户是否勾选 保存模版来确定
#    parentScope.$broadcast('openUploadFilePicker')
    if $scope.saveTemplate.checked
      if $scope.serverHasTemplate
        ApiService.updateProtectTemplate(postTemplateData,(data,scope)->
          console.log('---succ')
          Utils.success($translate.instant('Save Template Success'))
          if data && data.code==100000
            if data.data && data.data.length && data.data[0]
              Utils.templateData=data.data[0]
        ,(data)->
          Utils.warning(data.message)
        )
      else
        ApiService.addProtectTemplate(postTemplateData,(data,scope)->
          console.log('---succ')
          Utils.success($translate.instant('Save Template Success'))
          if data && data.code==100000
            if data.data && data.data.length && data.data[0]
              Utils.templateData=data.data[0]
        ,(data)->
          Utils.warning(data.message)
        )


    if !$scope.defaultTemplateMode
      postData={
        "cDocID": file.cDocId
        "fileLink": "",
        "notice": "0",
        "invitation": "0",
        "userList": userList
      }
      console.log('====postData====')
      console.log(postData)
      ApiService.setCdrmPermission(postData,(data)->
        console.log('---succ')
        $scope.loading=false
        $uibModalInstance.close()
        if data && data.ret==0
          Utils.success($translate.instant('set_perm_succ'))
      ,(data)->
        $scope.loading=false
        Utils.warning(data.message)
        $uibModalInstance.close()
      )
    else
      $uibModalInstance.close()
      if dropFiles
        parentScope.upload(dropFiles)
      else
        if !justShowTemplate
          parentScope.openUploadFilePicker()


  $scope.cancel=()->
#    $scope.defaultProtectTemplate=!$scope.defaultProtectTemplate
    $uibModalInstance.close()



.controller 'advancedSearchModal', ($scope,Utils,$translate, $uibModalInstance,chosenOptions,$filter,location,scope,searchType)->
  $scope.category=searchType||'document'
  chosenArr = []
  console.log('$scope.category',$scope.category)
  console.log(chosenOptions)

  # chosenOptions
  # 1.记录用户设置信息
  # 2.为了第二次打开还有上次的信息
  if !chosenOptions
    chosenOptions = {}
    # 解释下after     这个参数记录的是 如 今天是2018-03-30   chosenOptions.lastModification=today
    #                那么其对应的 chosenOptions.after.lastModification=2018-03-30 日期是cmis sql语句要求的
    #                而 today 是方便用户理解
    chosenOptions.after = {}
  else
    for type,arg of chosenOptions
      if type=='fileMineType'
        $scope['_type']=arg
        continue
      if type!='fileName'
        $scope['_'+type]=arg
      else
        $scope[type]=arg
      if chosenArr.indexOf(type)==-1
        chosenArr.push(type)

  # 显示 all document folder
  if !$scope['_type']
    $scope['_type']=searchType


  # 设置类型
  $scope.setTypeAndArg=(arg,type,dateOffset)->
    console.log(arg)
    console.log(type)
    console.log(dateOffset)
    # chosenArr 记录方便后面 reset
    if chosenArr.indexOf(type)==-1
      chosenArr.push(type)
    # 特殊处理下  all folder document

    if arg=='all' || arg=='folder' || arg=='document'
      $scope.category=arg
      $scope['fileMineType']=''
      chosenOptions['fileMineType']=''
    else
      #  如果是 'type' 需要区分下有两种情况  一种是 all folder document 还有一种 fileMineType
      if type=='type'
        type='fileMineType'
        $scope.category='document'

  #    if $scope[type]==arg
  #      $scope[type]=''
  #      chosenOptions[type]=''
  #      chosenOptions['after'][type]=''
  #    else
      $scope[type]=arg
      chosenOptions[type]=arg
      if typeof dateOffset=='number'
        z = $filter('date')(new Date().getTime() - dateOffset * 86400000, 'yyyy-MM-dd')
        chosenOptions['after'][type]=z
  $scope.setTypeAndArgBefore=(arg,type)=>
    if arg==''
      chosenOptions['after'][type]=''
      chosenOptions[type]=''
      return
    dateToNum={
      today:0
      yesterday:1
      within_last_week:7
      within_last_month:30
      within_90_days:90
      a_year_ago:365
    }
    $scope.setTypeAndArg(arg,type,dateToNum[arg])
  $scope.reset = ()->
    chosenOptions = {
      type:'all'
    }
    chosenOptions.after = {}
    # file name is special
    $scope.fileName=''
    $scope['fileMineType']=''
    if chosenArr.length==0
      return
    else
      console.log(chosenArr)
      for type in chosenArr
        $scope[type]=''
        $scope['_'+type]=''
    $scope['_type']='all'
  getValue =(obj,key)->
    # 防止对象不存在报错
    if obj && obj[key]
      return obj[key]
    else
      ''
  constructSentence = (key,value)->
    if key=='title' && !value
      return 'title=&'
    if value
      return ''+key+'='+value+'&'
    else
      return ''

  $scope.search=()->
    chosenOptions['fileName']=$scope.fileName
    if chosenOptions['fileName']
      if Utils.sqlContainIllegalChar(chosenOptions['fileName'])
        $translate('contain_illegal_char').then((result)->
          Utils.warning(result)
        )
        return

#   default sentence
    sentence = 'type='+$scope.category+'&'

#   也是 url 上面 显示的
#   暴露的数据 title -> fileName
#             lastModificationDateAfter -> lastModificationDateAfter
    #         lastAddedDateAfter -> lastAddedDateAfter
    #         lastViewedDateAfter -> lastViewedDateAfter
#             fileMineType -> fileMineType
#             fileAddedByDevice -> fileAddedByDevice

    title = getValue(chosenOptions,'fileName')
    lastModificationDateAfter = getValue(chosenOptions['after'],'lastModifiedDate')
    lastAddedDateAfter = getValue(chosenOptions['after'],'lastAddedDate')
    lastViewedDateAfter = getValue(chosenOptions['after'],'lastViewedDate')
    fileMineType = getValue(chosenOptions,'fileMineType')
    fileAddedByDevice = getValue(chosenOptions,'fileAddedBy')

    sentence += constructSentence('title',title)+constructSentence('lastModificationDateAfter',lastModificationDateAfter)+constructSentence('lastAddedDateAfter',lastAddedDateAfter)+constructSentence('lastViewedDateAfter',lastViewedDateAfter)+constructSentence('fileMineType',fileMineType)+constructSentence('fileAddedByDevice',fileAddedByDevice)
    sentence = sentence.slice(0,sentence.length-1)
    console.log '########'
    console.log(sentence)
    console.log(chosenOptions)
    console.log '########'
#    return false
    scope.search(null,null,sentence)
    Utils.sendGaEvent('OK','Advanced Search','')
    $uibModalInstance.close(chosenOptions)
  $scope.cancel=()->
    chosenOptions['fileName']=$scope.fileName

    $uibModalInstance.close(chosenOptions)





